package com.dokimall.cart.interceptor;


import com.dokimall.cart.vo.UserInfo;
import com.dokimall.common.constant.AuthServerConstant;
import com.dokimall.common.constant.CartConstant;
import com.dokimall.common.vo.MemberVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

public class CartInterceptor implements HandlerInterceptor {

    public static ThreadLocal<UserInfo> threadLocal = new ThreadLocal<>();
    // 在执行目标方法之前,判断用户的登录状态，并封装给Controller目标请求
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        UserInfo userInfo = new UserInfo();
        // 查看session中是否保存了用户的值
        HttpSession session = request.getSession();
        MemberVo attribute = (MemberVo) session.getAttribute(AuthServerConstant.LOGIN_USER);
        if(attribute!=null){
            // 用户已经登录
            userInfo.setUserId(attribute.getId());
        }
        // 查看是否有临时用户userKey
        Cookie[] cookies = request.getCookies();
        if (cookies !=null && cookies.length>0){
            for (Cookie cookie : cookies) {
                if(CartConstant.TEMP_USER_COOKIE_NAME.equals(cookie.getName())){
                    userInfo.setUserKey(cookie.getValue());
                    userInfo.setTempUser(true); //获取到了临时用户信息
                }
            }
        }
        // 如果没有临时用户一定要分配一个临时用户
        if (StringUtils.isEmpty(userInfo.getUserKey())) {
            String uuid = UUID.randomUUID().toString();
            userInfo.setUserKey(uuid);
        }
        // 全部放行
        threadLocal.set(userInfo);
        return true;
    }

    // 业务执行之后,分配临时用户，让浏览器保存
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // 拿到用户信息
        UserInfo userInfo = threadLocal.get();
        // 如果没有临时用户一定要保存一个临时用户
        if(!userInfo.getTempUser()){
            // 持续的延长临时用户的过期时间
            Cookie cookie = new Cookie("user-key",userInfo.getUserKey());
            cookie.setDomain("dokimall.com");
            cookie.setMaxAge(CartConstant.TEMP_USER_COOKIE_TIMEOUT);
            response.addCookie(cookie);
        }
    }
}
